package com.government.article.service.impl;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.DatePrinter;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.government.app.vo.KeywordSearchVO;
import com.government.area.domain.Area;
import com.government.area.mapper.AreaMapper;
import com.government.article.bo.ArticleBO;
import com.government.article.bo.ArticleInformationBO;
import com.government.article.bo.InformationCollectBO;
import com.government.article.domain.ArticleInformation;
import com.government.article.domain.ArticlePolicy;
import com.government.article.domain.ArticlePolicyRel;
import com.government.article.mapper.ArticleInformationMapper;
import com.government.article.mapper.ArticlePolicyMapper;
import com.government.article.mapper.ArticlePolicyRelMapper;
import com.government.article.vo.*;
import com.government.common.config.GovernmentConfig;
import com.government.common.core.domain.entity.SysDictData;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.core.domain.model.LoginUser;
import com.government.common.core.text.Convert;
import com.government.common.exception.ServiceException;
import com.government.common.utils.DateUtils;
import com.government.common.utils.SecurityUtils;
import com.government.common.utils.ServletUtils;
import com.government.common.utils.StringUtils;
import com.government.common.utils.file.FileUploadUtils;
import com.government.common.utils.file.FileUtils;
import com.government.member.domain.UserHobby;
import com.government.member.mapper.UserHobbyMapper;
import com.government.org.domain.OrgInfo;
import com.government.org.mapper.OrgInfoMapper;
import com.government.system.domain.FileUpload;
import com.government.system.domain.ImMail;
import com.government.system.domain.UploadFiles;
import com.government.system.domain.vo.WebAuthVo;
import com.government.system.mapper.ImMailMapper;
import com.government.system.mapper.UploadFilesMapper;
import com.government.system.service.ISysDictTypeService;
import com.government.system.service.WebRoleAuthService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.government.article.mapper.ArticleMapper;
import com.government.article.domain.Article;
import com.government.article.service.IArticleService;
import org.springframework.transaction.annotation.Transactional;

import static com.government.common.core.page.TableSupport.PAGE_NUM;
import static com.government.common.core.page.TableSupport.PAGE_SIZE;
import static com.government.common.utils.PageUtils.startPage;
import static com.government.common.utils.SecurityUtils.getLoginUser;


/**
 * 文章Service业务层处理
 *
 * @author system
 * @date 2023-09-20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleInformationMapper articleInformationMapper;

    @Autowired
    private ArticlePolicyRelMapper articlePolicyRelMapper;

    @Autowired
    private UserHobbyMapper userHobbyMapper;
    @Autowired
    private ArticlePolicyMapper articlePolicyMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private ImMailMapper messageMapper;
    @Autowired
    private OrgInfoMapper orgInfoMapper;
    @Autowired
    private UploadFilesMapper uploadFilesMapper;
    @Autowired
    private WebRoleAuthService webRoleAuthService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询文章
     *
     * @param articleId 文章主键
     * @return 文章
     */
    @Override
    public ArticleVO selectArticleByArticleId(Long articleId) {
        ArticleVO articleVO = articleMapper.selectArticleByArticleId(articleId);
        List<ArticlePolicyRel> articlePolicyRels = articlePolicyRelMapper.selectList(Wrappers.<ArticlePolicyRel>lambdaQuery().eq(ArticlePolicyRel::getArticleId, articleId));
        List<Long> categorys = articlePolicyRels.stream().map(ArticlePolicyRel::getPolicyId).collect(Collectors.toList());
        articleVO.setCategory(categorys);

        if (StrUtil.isNotBlank(articleVO.getAttachmentData())) {
            List<FileUpload> attachmentDataObj = Lists.newArrayList();
            String[] attachmentDatas = articleVO.getAttachmentData().split(",");
            for (String attachmentData : attachmentDatas) {
                if (StrUtil.isNotBlank(attachmentData)) {
                    UploadFiles uploadFiles = uploadFilesMapper.selectOne(Wrappers.<UploadFiles>lambdaQuery().eq(UploadFiles::getFileUrl, attachmentData));
                    if (Objects.nonNull(uploadFiles)) {
                        FileUpload fileUpload = new FileUpload();
                        if (StrUtil.isNotBlank(articleVO.getCompleteTime()) && DateUtil.parseDate(articleVO.getCompleteTime()).compareTo(DateUtil.parseDate("2023-10-01")) > 0) {
                            fileUpload.setName(uploadFiles.getFromName());
                        } else {
                            fileUpload.setName(uploadFiles.getFileUrl());
                        }
                        fileUpload.setUrl(uploadFiles.getFileUrl());
                        attachmentDataObj.add(fileUpload);
                    }
                }
            }
            articleVO.setAttachmentDataList(attachmentDataObj);
        }
        if (StrUtil.isNotBlank(articleVO.getWorkResult())) {

            List<FileUpload> workResultObj = Lists.newArrayList();
            String[] workResults = articleVO.getWorkResult().split(",");
            for (String workResult : workResults) {
                if (StrUtil.isNotBlank(workResult)) {
                    UploadFiles uploadFiles = uploadFilesMapper.selectOne(Wrappers.<UploadFiles>lambdaQuery().eq(UploadFiles::getFileUrl, workResult));
                    if (Objects.nonNull(uploadFiles)) {
                        FileUpload fileUpload = new FileUpload();
                        if (StrUtil.isNotBlank(articleVO.getCompleteTime()) && DateUtil.parseDate(articleVO.getCompleteTime()).compareTo(DateUtil.parseDate("2023-10-01")) > 0) {
                            fileUpload.setName(uploadFiles.getFromName());
                        } else {
                            fileUpload.setName(uploadFiles.getFileUrl());
                        }
                        fileUpload.setUrl(uploadFiles.getFileUrl());
                        workResultObj.add(fileUpload);
                    }
                }
            }

            articleVO.setWorkResultList(workResultObj);
        }

        if (StrUtil.isNotBlank(articleVO.getAttachmentData()) && articleVO.getAttachmentData().startsWith(",")) {
            articleVO.setAttachmentData(articleVO.getAttachmentData().substring(1));
        }
        if (StrUtil.isNotBlank(articleVO.getWorkResult()) && articleVO.getWorkResult().startsWith(",")) {
            articleVO.setWorkResult(articleVO.getWorkResult().substring(1));
        }
        if (StrUtil.isNotBlank(articleVO.getOrgId())) {
            articleVO.setOrgIdList(Arrays.asList(articleVO.getOrgId().split(",")));
        }
        return articleVO;
    }

    /**
     * 查询文章列表
     *
     * @return 文章
     */
    @Override
    public List<ArticleInformationVO> selectArticleList(ArticleInformationBO bo) {
        int pageNum = Convert.toInt(ServletUtils.getParameter(PAGE_NUM));
        int pageSize = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE));
        int startNo = pageNum * pageSize - pageSize;
        startPage();
        List<ArticleInformationVO> result = articleMapper.selectArticleList(bo);
        for (ArticleInformationVO item : result) {
            item.setNo(startNo + 1);
            startNo++;
        }
        return result;
    }

    /**
     * 新增文章
     *
     * @return 结果
     */
    @Override
    public int insertArticle(ArticleBO bo) {

        SysUser user = getLoginUser().getUser();
        Article article = new Article();
        ServiceException.throwExOnCondition(Objects.isNull(article), "文章不存在");

        ArticleInformation articleInformation = new ArticleInformation();
        articleInformation.setProof(bo.getProof());
        articleInformation.setCharacter(bo.getCharacter());
        articleInformation.setInstructions(bo.getInstructions());
        if (Objects.nonNull(bo.getCompleteTime())) {
            articleInformation.setCompleteTime(bo.getCompleteTime());
        } else {
            articleInformation.setCompleteTime(null);
        }
        articleInformation.setSource(bo.getSource());
        if (CollUtil.isNotEmpty(bo.getOrgIdList())) {
            articleInformation.setOrgId(String.join(",", bo.getOrgIdList()));
        } else {
            articleInformation.setOrgId("");
        }

        articleInformation.setYear(bo.getYear());
        articleInformation.setIsPublish(bo.getIsPublish());
        articleInformation.setSourceType(bo.getSourceType());
        articleInformation.setNavigation(bo.getNavigation());
        articleInformation.setAttachments(bo.getAttachments());
//        articleInformation.setWorkResult(bo.getWorkResult());
        if (CollUtil.isNotEmpty(bo.getWorkResultList())) {
            List<String> workResultStr = bo.getWorkResultList().stream().map(FileUpload::getUrl).collect(Collectors.toList());
            articleInformation.setWorkResult(String.join(",", workResultStr));
        }
        articleInformation.setSortTime(bo.getSortTime());
        // 性质为政策时，置顶该资讯
        if ("8".equals(bo.getCharacter())) {
            articleInformation.setIsTop("1");
        }
        // 发布时，设置发布时间和审核时间、审核状态
        if ("1".equals(bo.getIsPublish())) {

            if (Objects.isNull(articleInformation.getPublishTime())) {
                articleInformation.setPublishTime(new Date());
                article.setAuditBy(String.valueOf(user.getUserId()));
                article.setAuditTime(new Date());
            }
            article.setStstus("1");

            // 发送站内信
            sendMessage(articleInformation, user);
        }
        articleInformation.setCreateBy(String.valueOf(user.getUserId()));
        articleInformation.setCreateTime(DateUtils.getNowDate());
        articleInformation.setUpdateTime(DateUtils.getNowDate());
        articleInformation.setUpdateBy(String.valueOf(user.getUserId()));
//        article.setAttachmentData(bo.getAttachmentData());
        if (CollUtil.isNotEmpty(bo.getAttachmentDataList())) {
            List<String> attachmentDataStr = bo.getAttachmentDataList().stream().map(FileUpload::getUrl).collect(Collectors.toList());
            article.setAttachmentData(String.join(",", attachmentDataStr));
        }
        article.setTitle(bo.getTitle());
        article.setContent(bo.getContent());
        article.setType(67L);
        article.setTypeName("政策资讯");
        article.setCreateTime(DateUtils.getNowDate());
        article.setCreateBy(String.valueOf(user.getUserId()));
        article.setUpdateTime(DateUtils.getNowDate());
        article.setUpdateBy(String.valueOf(user.getUserId()));

        contentReplace(article, articleInformation);
        articleMapper.insert(article);

        if (CollUtil.isNotEmpty(bo.getCategory())) {

            for (Long category : bo.getCategory()) {
                ArticlePolicyRel articlePolicyRel = new ArticlePolicyRel();
                articlePolicyRel.setArticleId(article.getArticleId());
                articlePolicyRel.setPolicyId(category);
                articlePolicyRelMapper.insert(articlePolicyRel);

                ArticlePolicy articlePolicy = articlePolicyMapper.selectById(category);
                // 获取每条政策资讯下的最新批次最早的成文时间作为执行时间起点
//                ArticleInformation articleInformationTemp = articleInformationMapper.getProjectApprovalTime(category);
//                if (Objects.nonNull(articleInformationTemp)) {
//                    if (StrUtil.isNotBlank(bo.getYear()) && Objects.nonNull(bo.getCompleteTime())) {
//                        if (Integer.parseInt(bo.getYear()) > Integer.parseInt(articleInformationTemp.getYear())) {
//                            articlePolicy.setApprovalTime(bo.getCompleteTime());
//                        } else {
//                            articlePolicy.setApprovalTime(articleInformationTemp.getCompleteTime());
//                        }
//                    }
//                } else {
//                    articlePolicy.setApprovalTime(bo.getCompleteTime());
//                }
//                articlePolicyMapper.updateById(articlePolicy);
            }
        }
        articleInformation.setArticleId(article.getArticleId());
        return articleInformationMapper.insert(articleInformation);


    }

    private void contentReplace(Article article, ArticleInformation articleInformation) {
        String content = article.getContent();
        String attachments = articleInformation.getAttachments();
        String title = "《(.*?)》";
        Pattern titlePattern = Pattern.compile(title);
        String proof = "（(.*?)）";
        Pattern proofPattern = Pattern.compile(proof);
        if (StrUtil.isNotBlank(content)) {

            Matcher titleMatcher = titlePattern.matcher(content);
            while (titleMatcher.find()) {
                String data = titleMatcher.group(1);
                if (data.contains("@@") && data.contains("##")) {
                    String olddata = data;
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black;\">", "");
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("</span>", "");
                    String contentRegex = "@@(.*?)##";
                    Pattern contentPattern = Pattern.compile(contentRegex);
                    Matcher contentMatcher = contentPattern.matcher(data);
                    while (contentMatcher.find()) {
                        data = contentMatcher.group(1);
//                        data = data.substring(data.lastIndexOf("@") + 1, data.indexOf("#"));
                        String articleId = articleMapper.selectArticleIdByTitle(data, "");
                        if (StrUtil.isNotBlank(articleId)) {
                            content = content.replace("《" + olddata + "》", "《<a href='http://www.touce.com.cn/detail?id=" + articleId + "&searchType=1' target='_blank'>" + data + "</a>》");
                        } else {
                            content = content.replace("《" + olddata + "》", "《" + data + "》");
                        }
                    }
                }
            }

            Matcher proofMatcher = proofPattern.matcher(content);
            while (proofMatcher.find()) {
                String data = proofMatcher.group(1);
                if (data.contains("@@") && data.contains("##")) {
                    String olddata = data;
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black;\">", "");
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("</span>", "");
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋;\">", "");
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; text-indent: 21pt;\">", "");
                    String contentRegex = "@@(.*?)##";
                    Pattern contentPattern = Pattern.compile(contentRegex);
                    Matcher contentMatcher = contentPattern.matcher(data);
                    while (contentMatcher.find()) {
                        data = contentMatcher.group(1);
//                        data = data.substring(data.lastIndexOf("@") + 1, data.indexOf("#"));
                        String articleId = articleMapper.selectArticleIdByTitle("", data);
                        if (StrUtil.isNotBlank(articleId)) {
                            content = content.replace("（" + olddata + "）", "（<a href='http://www.touce.com.cn/detail?id=" + articleId + "&searchType=1' target='_blank'>" + data + "</a>）");
                        } else {
                            content = content.replace("（" + olddata + "）", "（" + data + "）");
                        }
                    }
                }
            }
            article.setContent(content);
        }
        if (StrUtil.isNotBlank(attachments)) {
            Matcher attachmentsTitleMatcher = titlePattern.matcher(attachments);
            while (attachmentsTitleMatcher.find()) {
                String data = attachmentsTitleMatcher.group(1);
                if (data.contains("@@") && data.contains("##")) {
                    String olddata = data;
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black;\">", "");
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("</span>", "");
                    String contentRegex = "@@(.*?)##";
                    Pattern contentPattern = Pattern.compile(contentRegex);
                    Matcher contentMatcher = contentPattern.matcher(data);
                    while (contentMatcher.find()) {
                        data = contentMatcher.group(1);
//                        data = data.substring(data.lastIndexOf("@") + 1, data.indexOf("#"));
                        String articleId = articleMapper.selectArticleIdByTitle(data, "");
                        if (StrUtil.isNotBlank(articleId)) {
                            attachments = attachments.replace("《" + olddata + "》", "《<a href='http://www.touce.com.cn/detail?id=" + articleId + "&searchType=1' target='_blank'>" + data + "</a>》");
                        } else {
                            attachments = attachments.replace("《" + olddata + "》", "《" + data + "》");
                        }
                    }
                }
            }

            Matcher attachmentsProofMatcher = proofPattern.matcher(attachments);
            while (attachmentsProofMatcher.find()) {
                String data = attachmentsProofMatcher.group(1);
                if (data.contains("@@") && data.contains("##")) {
                    String olddata = data;
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black;\">", "");
                    data = data.replace("<span style=\"font-family: 文鼎ＰＬ简报宋; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("<span lang=\"EN-US\" style=\"font-family: 'Times New Roman',serif; mso-fareast-font-family: 文鼎ＰＬ简报宋; mso-bidi-theme-font: minor-bidi; color: black; mso-themecolor: text1;\">", "");
                    data = data.replace("</span>", "");
                    String contentRegex = "@@(.*?)##";
                    Pattern contentPattern = Pattern.compile(contentRegex);
                    Matcher contentMatcher = contentPattern.matcher(data);
                    while (contentMatcher.find()) {
                        data = contentMatcher.group(1);
//                        data = data.substring(data.lastIndexOf("@") + 1, data.indexOf("#"));
                        String articleId = articleMapper.selectArticleIdByTitle("", data);
                        if (StrUtil.isNotBlank(articleId)) {
                            attachments = attachments.replace("（" + olddata + "）", "（<a href='http://www.touce.com.cn/detail?id=" + articleId + "&searchType=1' target='_blank'>" + data + "</a>）");
                        } else {
                            attachments = attachments.replace("（" + olddata + "）", "（" + data + "）");
                        }
                    }
                }
            }
            articleInformation.setAttachments(attachments);
        }
    }

    private void sendMessage(ArticleInformation articleInformation, SysUser user) {

        if ((DateUtil.parseDate("2024-01-01")).isBefore(articleInformation.getSortTime())) {
            // 给关注了该政策的用户发站内信
            if (StrUtil.isNotBlank(articleInformation.getCategory())) {
                List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType("information_nature");
                Map<String, String> informationNatureMap = sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                String[] policyIds = articleInformation.getCategory().split(",");
                List<Long> policyList = Lists.newArrayList();
                String policyName = "";
                for (String policyId : policyIds) {
                    if (StrUtil.isNotBlank(policyId)) {
                        policyList.add(Long.parseLong(policyId));
                        ArticlePolicy articlePolicy = articlePolicyMapper.selectOne(Wrappers.<ArticlePolicy>lambdaQuery().select(ArticlePolicy::getName).eq(ArticlePolicy::getArticleId, policyId));
                        if (Objects.nonNull(articlePolicy)) {
                            policyName = articlePolicy.getName();
                        }
                    }
                }
                String sortTime = DateUtil.format(articleInformation.getSortTime(), DatePattern.CHINESE_DATE_PATTERN);
                List<UserHobby> userHobbyList = userHobbyMapper.selectList(Wrappers.<UserHobby>lambdaQuery()
                        .in(UserHobby::getSourceId, policyList)
                        .eq(UserHobby::getSourceType, "2").eq(UserHobby::getType, "2"));
                for (UserHobby userHobby : userHobbyList) {
                    ImMail message = new ImMail();
                    message.setCreateTime(new Date());
                    message.setCreateBy(String.valueOf(user.getUserId()));
                    message.setBusinessId(articleInformation.getArticleId());
                    message.setContent(sortTime + "，您关注的“" + policyName + "”等政策更新了1条" + informationNatureMap.get(articleInformation.getCharacter()) + "资讯。");
                    message.setUserId(userHobby.getUserId());
                    messageMapper.insert(message);
                }
            }
        }

    }


    /**
     * 修改文章
     *
     * @param bo 文章
     * @return 结果
     */
    @Override
    public int updateArticle(ArticleBO bo) {

        SysUser user = getLoginUser().getUser();
        Article article = articleMapper.selectById(bo.getArticleId());
        ServiceException.throwExOnCondition(Objects.isNull(article), "文章不存在");

        ArticleInformation articleInformation = articleInformationMapper.selectOne(Wrappers.<ArticleInformation>lambdaQuery().eq(ArticleInformation::getArticleId, bo.getArticleId()));
        articleInformation.setProof(bo.getProof());
        articleInformation.setCharacter(bo.getCharacter());
        articleInformation.setInstructions(bo.getInstructions());
        if (Objects.nonNull(bo.getCompleteTime())) {
            articleInformation.setCompleteTime(bo.getCompleteTime());
        } else {
            articleInformation.setCompleteTime(null);
        }
        if (Objects.nonNull(bo.getSortTime())) {
            articleInformation.setSortTime(bo.getSortTime());
        } else {
            articleInformation.setSortTime(null);
        }
        articleInformation.setSource(bo.getSource());
        articleInformation.setYear(bo.getYear());
        if (CollUtil.isNotEmpty(bo.getOrgIdList())) {
            articleInformation.setOrgId(String.join(",", bo.getOrgIdList()));
        } else {
            articleInformation.setOrgId("");
        }
        articleInformation.setIsPublish(bo.getIsPublish());
        articleInformation.setSourceType(bo.getSourceType());
        articleInformation.setNavigation(bo.getNavigation());
        // 性质为政策时，置顶该资讯
        if ("8".equals(bo.getCharacter())) {
            articleInformation.setIsTop("1");
        }
        // 发布时，设置发布时间和审核时间、审核状态
        if ("1".equals(bo.getIsPublish())) {
            if (Objects.isNull(articleInformation.getPublishTime())) {
                articleInformation.setPublishTime(new Date());
                article.setAuditBy(String.valueOf(user.getUserId()));
                article.setAuditTime(new Date());
            }

            article.setStstus("1");

            // 发送站内信
            sendMessage(articleInformation, user);
        }

        if (CollUtil.isNotEmpty(bo.getCategory())) {

            articlePolicyRelMapper.delete(Wrappers.<ArticlePolicyRel>lambdaQuery().eq(ArticlePolicyRel::getArticleId, article.getArticleId()));

            List<String> policyIds = Lists.newArrayList();
            for (Long category : bo.getCategory()) {
                policyIds.add(String.valueOf(category));
                ArticlePolicyRel articlePolicyRel = new ArticlePolicyRel();
                articlePolicyRel.setArticleId(article.getArticleId());
                articlePolicyRel.setPolicyId(category);
                articlePolicyRelMapper.insert(articlePolicyRel);

//                ArticlePolicy articlePolicy = articlePolicyMapper.selectById(category);
//                // 获取每条政策资讯下的最新批次最早的成文时间作为执行时间起点
//                ArticleInformation articleInformationTemp = articleInformationMapper.getProjectApprovalTime(category);
//                if (Objects.nonNull(articleInformationTemp)) {
//                    if (StrUtil.isNotBlank(bo.getYear()) && Objects.nonNull(bo.getCompleteTime())) {
//                        if (Integer.parseInt(bo.getYear()) > Integer.parseInt(articleInformationTemp.getYear())) {
//                            articlePolicy.setApprovalTime(bo.getCompleteTime());
//                        } else {
//                            articlePolicy.setApprovalTime(articleInformationTemp.getCompleteTime());
//                        }
//                    }
//                } else {
//                    articlePolicy.setApprovalTime(bo.getCompleteTime());
//                }
//                articlePolicyMapper.updateById(articlePolicy);
            }
            articleInformation.setCategory(String.join(",", policyIds));
        } else {
            articlePolicyRelMapper.delete(Wrappers.<ArticlePolicyRel>lambdaQuery().eq(ArticlePolicyRel::getArticleId, article.getArticleId()));
            articleInformation.setCategory("");
        }

        articleInformation.setAttachments(bo.getAttachments());
        // 删除不需要的源文件
        if (StrUtil.isNotBlank(bo.getWorkResult())) {
            String[] workResults = bo.getWorkResult().split(",");
            List<String> workResultList = Arrays.asList(workResults);
            if (StrUtil.isNotBlank(articleInformation.getWorkResult())) {
                String[] workResultTemps = articleInformation.getWorkResult().split(",");
                for (String workResultTemp : workResultTemps) {
                    if (StrUtil.isNotBlank(workResultTemp)) {
                        if (!workResultList.contains(workResultTemp)) {
                            String filePath = GovernmentConfig.getProfile() + workResultTemp.substring(workResultTemp.lastIndexOf("/upload/"));
                            FileUtils.deleteFile(filePath);
                        }
                    }
                }
            }
        }
//        articleInformation.setWorkResult(bo.getWorkResult());

        if (CollUtil.isNotEmpty(bo.getWorkResultList())) {
            List<String> workResultStr = bo.getWorkResultList().stream().map(FileUpload::getUrl).collect(Collectors.toList());
            articleInformation.setWorkResult(String.join(",", workResultStr));
        }
        articleInformation.setSortTime(bo.getSortTime());
        articleInformation.setUpdateTime(DateUtils.getNowDate());
        articleInformation.setUpdateBy(String.valueOf(user.getUserId()));
        article.setContent(bo.getContent());
        contentReplace(article, articleInformation);
        articleInformationMapper.updateById(articleInformation);

        // 删除不需要的源文件
        if (StrUtil.isNotBlank(bo.getAttachmentData())) {
            String[] attachmentDatas = bo.getAttachmentData().split(",");
            List<String> attachmentDataList = Arrays.asList(attachmentDatas);
            if (StrUtil.isNotBlank(article.getAttachmentData())) {
                String[] attachmentDataTemps = article.getAttachmentData().split(",");
                for (String attachmentDataTemp : attachmentDataTemps) {
                    if (StrUtil.isNotBlank(attachmentDataTemp)) {
                        if (!attachmentDataList.contains(attachmentDataTemp)) {
                            String filePath = GovernmentConfig.getProfile() + attachmentDataTemp.substring(attachmentDataTemp.lastIndexOf("/upload/"));
                            FileUtils.deleteFile(filePath);
                        }
                    }
                }
            }
        }
//        article.setAttachmentData(bo.getAttachmentData());
        if (CollUtil.isNotEmpty(bo.getAttachmentDataList())) {
            List<String> attachmentDataStr = bo.getAttachmentDataList().stream().map(FileUpload::getUrl).collect(Collectors.toList());
            article.setAttachmentData(String.join(",", attachmentDataStr));
        }
        article.setTitle(bo.getTitle());

        article.setUpdateTime(DateUtils.getNowDate());
        article.setUpdateBy(String.valueOf(user.getUserId()));
        return articleMapper.updateArticle(article);
    }

    /**
     * 批量删除文章
     *
     * @param articleIds 需要删除的文章主键
     * @return 结果
     */
    @Override
    public int deleteArticleByArticleIds(Long[] articleIds) {
        return articleMapper.deleteArticleByArticleIds(articleIds);
    }

    /**
     * 删除文章信息
     *
     * @param articleIds 文章主键
     * @return 结果
     */
    @Override
    public void deleteArticleByArticleId(Long[] articleIds) {
        for (Long articleId : articleIds) {
            Article article = articleMapper.selectById(articleId);
            article.setIsDeleted("1");
            article.setUpdateTime(new Date());
            article.setUpdateBy(String.valueOf(getLoginUser().getUserId()));

            ArticleInformation articleInformation = articleInformationMapper.selectOne(Wrappers.<ArticleInformation>lambdaQuery().eq(ArticleInformation::getArticleId, articleId));
            articleInformation.setIsDeleted("1");
            articleInformation.setUpdateTime(new Date());
            articleInformation.setUpdateBy(String.valueOf(getLoginUser().getUserId()));
            articleInformationMapper.updateById(articleInformation);
            articleMapper.updateById(article);
        }
    }

    @Override
    public void articleDataHandler() {
        List<Article> articleList = articleMapper.selectArticleHandler();
        for (Article article : articleList) {
            String[] titles = article.getTitle().split(" ");
//            ArticleInformation articleInformation = articleInformationMapper.selectOne(Wrappers.<ArticleInformation>lambdaQuery().eq(ArticleInformation::getArticleId, article.getArticleId()));
//            if (titles.length == 3) {
//
//                if (titles[2].contains("〔")) {
//                    articleInformation.setProof(titles[2]);
//                } else {
//                    articleInformation.setInstructions(titles[2]);
//                }
//            } else if (titles.length == 4) {
//                articleInformation.setProof(titles[2]);
//                articleInformation.setInstructions(titles[3]);
//            }
            if (titles.length > 1) {
                article.setTitle(titles[1]);

                articleMapper.updateById(article);
            }
//            articleInformationMapper.updateById(articleInformation);
        }
    }

    @Override
    public void articlePolicyRelHandler() {
        List<ArticleInformation> articleInformations = articleInformationMapper.selectList(Wrappers.<ArticleInformation>lambdaQuery().isNotNull(ArticleInformation::getCategory));
        for (ArticleInformation articleInformation : articleInformations) {
            String[] categorys = articleInformation.getCategory().split(",");
            for (String category : categorys) {
                if (StrUtil.isNotBlank(category)) {
                    ArticlePolicyRel articlePolicyRel = new ArticlePolicyRel();
                    articlePolicyRel.setArticleId(articleInformation.getArticleId());
                    articlePolicyRel.setPolicyId(Long.parseLong(category));
                    articlePolicyRelMapper.insert(articlePolicyRel);
                }
            }
        }
    }

    @Override
    public void deleteArticle(Long[] articleIds) {
        for (Long articleId : articleIds) {
            Article article = articleMapper.selectById(articleId);
            article.setIsDeleted("1");
            article.setUpdateTime(new Date());
            article.setUpdateBy(String.valueOf(getLoginUser().getUserId()));
            articleMapper.updateById(article);
        }
    }

    @Override
    public void favorites(UserHobby userHobby) {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();

        UserHobby userHobbyTemp = userHobbyMapper.selectOne(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, user.getUserId())
                .eq(UserHobby::getSourceId, userHobby.getSourceId())
                .eq(UserHobby::getType, userHobby.getType())
                .eq(UserHobby::getSourceType, userHobby.getSourceType()));

        Date now = DateUtil.date();
        Article article = null;
        OrgInfo orgInfo = null;
        if ("1".equals(userHobby.getSourceType()) || "2".equals(userHobby.getSourceType())) {
            article = articleMapper.selectById(userHobby.getSourceId());

            if (Objects.nonNull(userHobbyTemp)) {

                userHobbyMapper.deleteById(userHobbyTemp.getId());
                if ("1".equals(userHobby.getType())) {
                    article.setLikeNum(article.getLikeNum() - 1);
                } else {
                    article.setCollectNum(article.getCollectNum() - 1);
                }
                articleMapper.updateById(article);
            } else {

                if ("1".equals(userHobby.getType())) {
                    article.setLikeNum(article.getLikeNum() + 1);
                } else {
                    if (!SysUser.isAdmin(user.getUserId())) {
                        // 收藏数量限制
                        int cc = Integer.parseInt(webAuthVo.getCc());
                        // 关注数量限制
                        int fc = Integer.parseInt(webAuthVo.getFc());
                        if ("1".equals(userHobby.getSourceType())) {
                            int userCc = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, user.getUserId())
                                    .eq(UserHobby::getType, userHobby.getType())
                                    .eq(UserHobby::getSourceType, "1"));
                            if (userCc >= cc) {
                                throw new ServiceException("当前收藏数量已达上线，开通更高级别会员可获得更多权益", 400001);
                            }
                        }
                        if ("2".equals(userHobby.getSourceType())) {

                            int userFc = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, user.getUserId())
                                    .eq(UserHobby::getType, userHobby.getType())
                                    .eq(UserHobby::getSourceType, "2"));
                            if (userFc >= fc) {
                                throw new ServiceException("当前关注数量已达上线，开通更高级别会员可获得更多权益", 400001);
                            }
                        }
                    }
                    article.setCollectNum(article.getCollectNum() + 1);
                }


                userHobby.setCreateTime(now);
                userHobby.setCreateBy(String.valueOf(user.getUserId()));
                userHobby.setUserId(user.getUserId());
                userHobby.setTitle(article.getTitle());
                userHobbyMapper.insert(userHobby);

                articleMapper.updateById(article);
            }

        } else {
            orgInfo = orgInfoMapper.selectById(userHobby.getSourceId());
            if (Objects.nonNull(userHobbyTemp)) {

                userHobbyMapper.deleteById(userHobbyTemp.getId());
                if ("1".equals(userHobby.getType())) {
                    orgInfo.setLikeNum(orgInfo.getLikeNum() - 1);
                } else {
                    orgInfo.setCollectNum(orgInfo.getCollectNum() - 1);
                }
                orgInfoMapper.updateById(orgInfo);
            } else {
                userHobby.setCreateTime(now);
                userHobby.setCreateBy(String.valueOf(user.getUserId()));
                userHobby.setUserId(user.getUserId());
                userHobby.setTitle(orgInfo.getOrgName());
                userHobbyMapper.insert(userHobby);
                if ("1".equals(userHobby.getType())) {
                    orgInfo.setLikeNum(orgInfo.getLikeNum() + 1);
                } else {
                    if (!SysUser.isAdmin(user.getUserId())) {
                        // 收藏数量限制
                        int cc = Integer.parseInt(webAuthVo.getCc());
                        if ("3".equals(userHobby.getSourceType())) {
                            int userCc = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, user.getUserId())
                                    .eq(UserHobby::getType, userHobby.getType())
                                    .eq(UserHobby::getSourceType, "1"));
                            if (userCc >= cc) {
                                throw new ServiceException("当前收藏数量已达上线，开通更高级别会员可获得更多权益", 400001);
                            }
                        }
                    }
                    orgInfo.setCollectNum(orgInfo.getCollectNum() + 1);
                }
                orgInfoMapper.updateById(orgInfo);
            }
        }

    }

    @Override
    public void cancelFavorites(List<Long> collectIds) {
        List<UserHobby> userHobbyList = userHobbyMapper.selectList(Wrappers.<UserHobby>lambdaQuery().in(UserHobby::getId, collectIds));
        List<Long> articleIds = userHobbyList.stream().map(UserHobby::getSourceId).collect(Collectors.toList());
        userHobbyMapper.delete(Wrappers.<UserHobby>lambdaQuery().in(UserHobby::getId, collectIds));
        articleMapper.collectReduce(articleIds);
    }

    @Override
    public void batchFollow(List<Long> collectIds) {

        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();

        for (Long collectId : collectIds) {

            Article article = articleMapper.selectById(collectId);

            UserHobby userHobbyTemp = userHobbyMapper.selectOne(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, user.getUserId())
                    .eq(UserHobby::getSourceId, collectId)
                    .eq(UserHobby::getType, "2")
                    .eq(UserHobby::getSourceType, "2"));

            if (Objects.isNull(userHobbyTemp)) {

                if (!SysUser.isAdmin(user.getUserId())) {
                    // 关注数量限制
                    int fc = Integer.parseInt(webAuthVo.getFc());

                    int userFc = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, user.getUserId())
                            .eq(UserHobby::getType, "2")
                            .eq(UserHobby::getSourceType, "2"));
                    if (userFc >= fc) {
                        throw new ServiceException("当前关注数量已达上线，开通更高级别会员可获得更多权益", 400001);
                    }
                }
                article.setCollectNum(article.getCollectNum() + 1);

                Date now = DateUtil.date();
                UserHobby userHobby = new UserHobby();
                userHobby.setSourceId(collectId);
                userHobby.setSourceType("2");
                userHobby.setType("2");
                userHobby.setCreateTime(now);
                userHobby.setCreateBy(String.valueOf(user.getUserId()));
                userHobby.setUserId(user.getUserId());
                userHobby.setTitle(article.getTitle());
                userHobbyMapper.insert(userHobby);
                articleMapper.updateById(article);
            }
        }
    }


    @Override
    public void browseNumAdd(Long articleId) {

        articleMapper.browseAdd(articleId);
    }

//    /**
//     * 根据条件查询资讯汇总
//     *
//     * @param
//     */
//    @Override
//    public InformationCollectVO getInformationCollect(InformationCollectBO bo) {
//        InformationCollectVO informationCollectVO = new InformationCollectVO();
//        LoginUser login = getLoginUser();
//        SysUser currentUser = null;
//        // 获取当前的用户
//        if (StringUtils.isNotNull(login) && !login.isVisitor()) {
//            currentUser = login.getUser();
//        }
//
//        // 查询包含子级政策的所有资讯
//        if (StrUtil.isNotBlank(bo.getPolicyId())) {
//            List<String> policyIds = Lists.newArrayList();
//            policyIds.add(bo.getPolicyId());
//            bo.setPolicyIds(policyIds);
//            getAllChildPolicyId(bo.getPolicyId(), policyIds);
//        }
//        List<InformationCollectDetailVO> result = articleInformationMapper.getInformationCollect(bo);
////        bo.setIsTop("1");
////        List<InformationCollectDetailVO> topResult = articleInformationMapper.getInformationCollect(bo);
//
//        List<Long> sourceIds = Lists.newArrayList();
////        for (InformationCollectDetailVO item : topResult) {
////            sourceIds.add(item.getId());
////        }
//        for (InformationCollectDetailVO item : result) {
//            sourceIds.add(item.getId());
//        }
//
//        List<Long> likeFlagIds = Lists.newArrayList();
//        List<Long> collectFlagIds = Lists.newArrayList();
//        if (Objects.nonNull(currentUser) && CollUtil.isNotEmpty(result)) {
//            UserHobby query = new UserHobby();
//            query.setUserId(currentUser.getUserId());
//            query.setSourceIds(sourceIds);
//            query.setType("1");
//            query.setSourceType("1");
//            likeFlagIds = userHobbyMapper.getUserHobbyFlag(query);
//            query.setType("2");
//            collectFlagIds = userHobbyMapper.getUserHobbyFlag(query);
//        }
//
//        for (InformationCollectDetailVO item : result) {
//
//            if (Objects.nonNull(currentUser)) {
//
//                if (likeFlagIds.contains(item.getId())) {
//                    item.setIsLike("1");
//                }
//                if (collectFlagIds.contains(item.getId())) {
//                    item.setIsCollect("1");
//                }
//            }
//            item.setPublishTimeStr(DateUtil.formatDateTime(item.getPublishTime()));
//            item.setNew(DateUtil.between(item.getPublishTime(), DateUtil.date(), DateUnit.HOUR, true) <= 7);
//        }
//        if (CollUtil.isNotEmpty(result)) {
//            Map<String, List<InformationCollectDetailVO>> batchMap = result.stream().collect(Collectors.groupingBy(InformationCollectDetailVO::getYear));
//            List<InformationCollectBatchVO> batchVOList = Lists.newArrayList();
//            for (Map.Entry<String, List<InformationCollectDetailVO>> stringListEntry : batchMap.entrySet()) {
//                InformationCollectBatchVO informationCollectBatchVO = new InformationCollectBatchVO();
//                informationCollectBatchVO.setYear(stringListEntry.getKey());
//                List<InformationCollectDetailVO> list = stringListEntry.getValue().stream().sorted(Comparator.comparing(InformationCollectDetailVO::getCompleteTime).reversed()).collect(Collectors.toList());
//                informationCollectBatchVO.setInformationList(list);
//                batchVOList.add(informationCollectBatchVO);
//            }
//            Collections.sort(batchVOList, Comparator.comparing(InformationCollectBatchVO::getYear).reversed());
//            informationCollectVO.setBatchInformationList(batchVOList);
//        }
//
////        for (InformationCollectDetailVO item : topResult) {
////
////            if (Objects.nonNull(currentUser)) {
////
////                if(likeFlagIds.contains(item.getId())){
////                    item.setIsLike("1");
////                }
////                if(collectFlagIds.contains(item.getId())){
////                    item.setIsCollect("1");
////                }
////            }
////
////            item.setPublishTimeStr(DateUtil.formatDateTime(item.getPublishTime()));
//////            item.setNew(DateUtil.between(item.gets(), DateUtil.date(), DateUnit.HOUR, true) <= 7);
////
////        }
////        informationCollectVO.setTopInformationList(topResult);
//        return informationCollectVO;
//    }


    /**
     * 根据条件查询资讯汇总
     *
     * @param
     */
    @Override
    public List<InformationCollectDetailVO> getInformationCollect(InformationCollectBO bo) {
        LoginUser login = getLoginUser();
        SysUser currentUser = null;
        // 获取当前的用户
        if (StringUtils.isNotNull(login) && !login.isVisitor()) {
            currentUser = login.getUser();
        }

        // 查询包含子级政策的所有资讯
        if (StrUtil.isNotBlank(bo.getPolicyId())) {
            List<String> policyIds = Lists.newArrayList();
            policyIds.add(bo.getPolicyId());
            bo.setPolicyIds(policyIds);
            getAllChildPolicyId(bo.getPolicyId(), policyIds);
        }
        int pageNum = Convert.toInt(ServletUtils.getParameter(PAGE_NUM));
        int pageSize = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE));
        startPage();
        List<InformationCollectDetailVO> result = articleInformationMapper.getInformationCollect(bo);
//        bo.setIsTop("1");
//        List<InformationCollectDetailVO> topResult = articleInformationMapper.getInformationCollect(bo);

        List<Long> sourceIds = Lists.newArrayList();
//        for (InformationCollectDetailVO item : topResult) {
//            sourceIds.add(item.getId());
//        }
        for (InformationCollectDetailVO item : result) {
            sourceIds.add(item.getId());
        }

        List<Long> likeFlagIds = Lists.newArrayList();
        List<Long> collectFlagIds = Lists.newArrayList();
        if (Objects.nonNull(currentUser) && CollUtil.isNotEmpty(result)) {
            UserHobby query = new UserHobby();
            query.setUserId(currentUser.getUserId());
            query.setSourceIds(sourceIds);
            query.setType("1");
            query.setSourceType("1");
            likeFlagIds = userHobbyMapper.getUserHobbyFlag(query);
            query.setType("2");
            collectFlagIds = userHobbyMapper.getUserHobbyFlag(query);
        }

        for (InformationCollectDetailVO item : result) {

            if (Objects.nonNull(currentUser)) {

                if (likeFlagIds.contains(item.getId())) {
                    item.setIsLike("1");
                }
                if (collectFlagIds.contains(item.getId())) {
                    item.setIsCollect("1");
                }
            }
            item.setPublishTimeStr(DateUtil.formatDateTime(item.getPublishTime()));
            item.setNew(DateUtil.between(item.getPublishTime(), DateUtil.date(), DateUnit.HOUR, true) <= 7);
        }
        return result;
    }

    private void getAllChildPolicyId(String articleId, List<String> policyIds) {
        List<ArticlePolicy> articlePolicy = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery()
                .select(ArticlePolicy::getArticleId).eq(ArticlePolicy::getParentId, articleId));
        if (CollUtil.isNotEmpty(articlePolicy)) {
            for (ArticlePolicy policy : articlePolicy) {
                String policyId = String.valueOf(policy.getArticleId());
                policyIds.add(policyId);
                getAllChildPolicyId(policyId, policyIds);
            }
        }
    }

}
